import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:study_demo/api/bean.dart';
import 'package:study_demo/base/BaseController.dart';
import 'package:study_demo/base/json_transform_model_controller.dart';
import 'package:study_demo/db/isar.dart';
import 'package:study_demo/ui/tool/adb/input_dialog.dart';

import '../../../util/utils.dart';

class ApiToolController extends BaseController
    with
        GetSingleTickerProviderStateMixin,
        JsonTransformModelController,
        LocalDataApiInfo {
  final requestMethod = 'GET'.obs;
  final result = ''.obs;
  final type = 1.obs;

  final requestMethods = ['GET', 'POST'];
  final statusCode = 0.obs;

  final apiInfoList = [].obs;

  TextEditingController _urlEditingController = TextEditingController();

  TextEditingController get urlEditingController => _urlEditingController;

  TextEditingController _contentEditingController = TextEditingController();

  TextEditingController get contentEditingController =>
      _contentEditingController;

  TabController? tabController;

  @override
  onInit() async {
    super.onInit();
    tabController = TabController(length: 2, vsync: this);
    tabController!.index = 1;
    tabController!.addListener(() {
      if (tabController!.index != tabController!.animation!.value) return;
      type.value = tabController!.index;
    });
    await queryApiInfo();
    apiInfoList.assignAll(apiInfos);
  }

  send() async {
    String url = StringTrim(_urlEditingController.text);
    String content = StringTrim(_contentEditingController.text);
    if (!isValidJson(content)) {
      toast('输入的内容不是json格式,请先格式化');
      return;
    }
    // if (!isValidUrl(url)) {
    //   toast('你输入的url不合法');
    //   return;
    // }
    // Dio dio = Dio();
    // var response = await dio.request(url);
    // print('response:${response.data}');
    // _resultTextEditingController.text = response.data;
    if (requestMethod.value == 'GET') {
      Map<String, dynamic> data = jsonDecode(content);
      String code = data['code'];
      String info = jsonEncode(data['info']);
      print('code:$code');
      print('info:$info');
      api.getYz(RequestModel(code, info), url, success: (json, status) {
        resultTextEditingController.text = json.toString();
        statusCode.value = status;
      });
    }
  }

  clearUrl() {
    _urlEditingController.text = '';
  }

  apiGet() {
    String info = _contentEditingController.text.toString().trim();
  }

  format() {
    String content = _contentEditingController.text;
    if (!isValidJson(content)) {
      int index1 = content.indexOf('code:');
      int index2 = content.indexOf(',');
      String codeValue = '\"' + content.substring(index1 + 6, index2) + '\"';
      content = content.substring(0, index1 + 6) +
          codeValue +
          content.substring(index2);
      print('codeValue:$codeValue');
      contentEditingController.text = content
          .replaceFirst('code', '\"code\"')
          .replaceFirst('info', '\"info\"')
          .replaceFirst('userid', '\"userid\"', content.length - 12)
          .replaceFirst('snum', '\"snum\"');
    }
  }

  save() async {
    var result =
        await Get.dialog(InputDialog(title: '接口名称', hintText: '请输入接口名称'));
    print('result:$result');
    if (result != null && result.toString().isNotEmpty) {
      if (!isExist(result)) {
        Random random = Random();
        ApiInfo apiInfo = ApiInfo();
        apiInfo.id = random.nextInt(10000);
        apiInfo.name = result;
        apiInfo.url = StringTrim(_urlEditingController.text);
        apiInfo.info = StringTrim(_contentEditingController.text);
        apiInfos.save(apiInfo);
        toast('保存成功');
        await queryApiInfo();
        apiInfoList.assignAll(apiInfos);
      }
    }
  }

  bool isExist(String name) {
    bool flag = false;
    apiInfos.forEach((element) {
      if (element.name!.contains(name)) {
        flag = true;
      }
    });

    return flag;
  }

  chooseApi(ApiInfo apiInfo) {
    _urlEditingController.text = apiInfo.url!;
    _contentEditingController.text = apiInfo.info!;
  }

  deleteApi(String name) {
    apiInfos.delete(name);
    apiInfoList.removeWhere((it) => it.name == name);
  }
}
